package operation;

import book.Book;
import book.BookList;

import java.util.Scanner;

public class DelOperation implements IOPeration{
    public void work(BookList bookList) {
        System.out.println("删除图书！");

        // 输入这本书
        System.out.println("请输入要删除的书:");
        Scanner scanner = new Scanner(System.in);
        String name = scanner.nextLine();

        // 如果没有这本书就直接返回
        // 如果有这本书就把它的下标记录下来
        int useSize = bookList.getUsedSize();
        int k = 0;
        int i = 0;
        for(i = 0;i < useSize;i++){
            Book book = bookList.getBook(i);
            if(book.getName().equals(name)){
                k = i;
                break;
            }
        }
        if(i == useSize) {
            System.out.println("没有你要删除的图书!");
            return;
        }

        // 从后往前覆盖删除
        // 1 2 3 4
        Book[] books = bookList.getBooks();
        for(int j = k;j < useSize - 1;j++){
            books[j] = books[j + 1];
        }
        books[useSize - 1] = null;

        // 将最后一本书置为空,并且有效书的个数减一
        bookList.setUsedSize(useSize - 1);
        System.out.println("删除成功!");
    }
}
